package model.datareader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import model.exception.FileReadException;

/**
 * 
 * @author Jei Min Yoo
 * @author Michael Deng (edited)
 *
 */
public class TMLReader extends AbstractReader {

    private static final String CORRECT_WEBSITE = "http://www.sports-reference.com/cbb/coaches/";

    private URL myURL;
    private List<List<String>> myData;

    /**
     * TML reader constructor
     */
    public TMLReader () {
        super();
    }

    @Override
    public void readFile (String urltext) {
        myData = super.getData();
        myURL = getURL(urltext);
        super.readFile(urltext);
    }

    @Override
    protected void extractData () {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(myURL.openStream()));
            parseLines(reader);
            reader.close();
        }
        catch (IOException e) {
            throw new FileReadException("IO Exception.");
        }
    }

    private void parseLines (BufferedReader reader) throws IOException {
        String line;
        boolean inMyTable = false;
        while ((line = reader.readLine()) != null) {
            inMyTable = findMyTable(line, inMyTable);
            if (inMyTable) {
                addData(line);
            }
        }
    }

    private void addData (String line) {
        if (line.contains("/td>") || line.contains("/th>")) {
            String dataInput = cutHTMLTags(line);
            myData.get(myData.size() - 1).add(dataInput);
        }

        if (line.contains("<tr")) {
            myData.add(new ArrayList<String>());
        }
    }

    private boolean findMyTable (String line, boolean inMyTable) {
        if (line.contains("table class=\"sortable  stats_table")) {
            inMyTable = true;
        }
        if (line.contains("</table>")) {
            inMyTable = false;
        }
        return inMyTable;
    }

    private URL getURL (String urltext) {
        if (!urltext.contains(CORRECT_WEBSITE)) {
            throw new FileReadException("Website is incorrect!");
        }
        URL url = null;
        try {
            url = new URL(urltext);
        }
        catch (MalformedURLException e) {
            throw new FileReadException("URL is bad!");
        }
        return url;
    }

    private String cutHTMLTags (String s) {
        String result = s;
        while (result.contains("<") && result.contains(">")) {
            Stack<Character> stack = new Stack<Character>();
            int start = result.indexOf('<');
            stack.push('<');
            int index = start;
            while (!stack.isEmpty()) {
                index++;
                if (result.charAt(index) == '>') {
                    stack.pop();
                }
                else if (result.charAt(index) == '<') {
                    stack.push('<');
                }
            }
            result = result.substring(0, start) + result.substring(index + 1, result.length());
        }
        result = result.replaceAll("&nbsp;", " ");
        return result.trim();
    }
}
